<template>
  <div class="statistics-analysis-page">
    <h2 class="page-title">统计分析</h2>

    <!-- 下拉框区域 -->
    <el-card class="filter-card">
      <div class="filter-row">
        <!-- 第一层 -->
        <el-select
            v-model="firstSelect"
            placeholder="请选择分析维度"
            @change="handleFirstSelect"
        >
          <el-option label="毕业年份" value="year" />
          <el-option label="专业" value="major" />
          <el-option label="指导教师" value="teacher" />
        </el-select>

        <!-- 第二层 -->
        <el-select
            v-if="secondOptions.length"
            v-model="secondSelect"
            :multiple="allowMultiSecond"
            :placeholder="secondPlaceholder"
            @change="handleSecondSelect"
        >
          <el-option
              v-for="item in secondOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value"
          />
        </el-select>

        <!-- 第三层 -->
        <el-select
            v-if="thirdOptions.length"
            v-model="thirdSelect"
            :multiple="allowMultiThird"
            :placeholder="thirdPlaceholder"
            @change="handleThirdSelect"
        >
          <el-option
              v-for="item in thirdOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value"
          />
        </el-select>

        <!-- 第四层（仅在第一个选年份时才出现） -->
        <el-select
            v-if="fourthOptions.length"
            v-model="fourthSelect"
            :multiple="allowMultiFourth"
            :placeholder="fourthPlaceholder"
            @change="handleFourthSelect"
        >
          <el-option
              v-for="item in fourthOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value"
          />
        </el-select>
      </div>
    </el-card>

    <!-- 图表区域 -->
    <div class="chart-section">
      <div class="chart-container">
        <div ref="radarChartRef" class="chart" />
        <div ref="barLineChartRef" class="chart" />
      </div>
    </div>

    <!-- 表格 -->
    <el-card class="table-card">
      <el-table :data="tableData" style="width: 100%">
        <el-table-column prop="name" label="名称" />
        <el-table-column prop="score" label="分数" />
        <el-table-column prop="rank" label="排名" />
      </el-table>
    </el-card>
  </div>
</template>

<script setup>
import { ref, nextTick } from "vue";
import * as echarts from "echarts";
import axios from "@/utils/request";
import { ElMessage } from "element-plus";
import {
  getAllMajorsByYearSA,
  getAllMajorsSA, getAllTeachersByYearSA,
  getAllTeachersSA,
  getAllYearsByMajorSA,
  getAllYearsByTeacherSA,
  getAllYearsSA
} from "@/api/facultyAdmin.js";

const firstSelect = ref("");
const secondSelect = ref(null);
const thirdSelect = ref(null);
const fourthSelect = ref(null);

// 下拉框数据
const secondOptions = ref([]);
const thirdOptions = ref([]);
const fourthOptions = ref([]);

// 多选控制
const allowMultiSecond = ref(false);
const allowMultiThird = ref(false);
const allowMultiFourth = ref(false);

// 占位提示
const secondPlaceholder = ref("");
const thirdPlaceholder = ref("");
const fourthPlaceholder = ref("");

// 图表
const radarChartRef = ref();
const barLineChartRef = ref();
let radarChart, barLineChart;
const tableData = ref([]);

// ---------------------------
// 第一层选择
// ---------------------------
const handleFirstSelect = async (val) => {
  secondSelect.value = null;
  thirdSelect.value = null;
  fourthSelect.value = null;
  secondOptions.value = [];
  thirdOptions.value = [];
  fourthOptions.value = [];
  if (val === "year") {
    // 获取所有年份
    const yearRes = await getAllYearsSA()
    if (yearRes.code === 1 && yearRes.data) {
      secondOptions.value = yearRes.data.map((y) => ({
        label: y,
        value: y
      }))
    }
    secondPlaceholder.value = "请选择毕业年份";
  } else if (val === "major") {
    const majorRes = await getAllMajorsSA()
    if (majorRes.code === 1 && majorRes.data) {
      secondOptions.value = majorRes.data.map((m) => ({
        label: m,
        value: m
      }))
    }
    secondPlaceholder.value = "请选择专业";
  } else if (val === "teacher") {
    const TeacherRes = await getAllTeachersSA()
    if (TeacherRes.code === 1 && TeacherRes.data) {
      secondOptions.value = TeacherRes.data.map((t) => ({
        label: `${t.teacherName} (${t.teacherAccount})`,
        value: t.teacherAccount
      }))
    }
    secondPlaceholder.value = "请选择指导教师";
  }
};

// ---------------------------
// 第二层选择
// ---------------------------
const handleSecondSelect = async (val) => {
  thirdOptions.value = [];
  fourthOptions.value = [];
  thirdSelect.value = null;
  fourthSelect.value = null;

  if (firstSelect.value === "year") {
    // 第二层是具体年份 → 下一层选择“ 专业 / 老师 ”
    thirdOptions.value = [
      { label: "专业", value: "major" },
      { label: "指导教师", value: "teacher" },
    ];
    thirdPlaceholder.value = "请选择分析维度";
  } else if (firstSelect.value === "major") {
    const majorRes = await getAllYearsByMajorSA({
      major: val
    })
    if (majorRes.code === 1 && majorRes.data) {
      thirdOptions.value = majorRes.data.map((y) => ({
        label: y,
        value: y
      }))
    }
    thirdPlaceholder.value = "请选择年份";
    allowMultiThird.value = true;
  } else if (firstSelect.value === "teacher") {
    const teacherRes = await getAllYearsByTeacherSA({
      teacherAccount: val
    })
    if (teacherRes.code === 1 && teacherRes.data) {
      thirdOptions.value = teacherRes.data.map((y) => ({
        label: y,
        value: y
      }))
    }
    thirdPlaceholder.value = "请选择年份";
    allowMultiThird.value = true;
  }
};

// ---------------------------
// 第三层选择（年份分支下的“专业 or 教师”）
// ---------------------------
const handleThirdSelect = async (val) => {
  fourthOptions.value = [];
  fourthSelect.value = null;

  if (firstSelect.value === "year" && val === "major") {
    const majorRes = await getAllMajorsByYearSA({
      year: secondSelect.value
    })
    if (majorRes.code === 1 && majorRes.data) {
      fourthOptions.value = majorRes.data.map((m) => ({
        label: m,
        value: m
      }))
    }
    fourthPlaceholder.value = "请选择专业";
    allowMultiFourth.value = true;
  } else if (firstSelect.value === "year" && val === "teacher") {
      const teacherRes = await getAllTeachersByYearSA({
        year: secondSelect.value
      })
      if (teacherRes.code === 1 && teacherRes.data) {
        fourthOptions.value = teacherRes.data.map((t) => ({
          label: `${t.teacherName} (${t.teacherAccount})`,
          value: t.teacherAccount
        }))
      }
      fourthPlaceholder.value = "请选择指导教师";
      allowMultiFourth.value = true;
  } else {
    // 其他分支（major/teacher）直接加载数据
    await handleFourthSelect(val);
  }
};

// ---------------------------
// 第四层选择（最终触发数据加载）
// ---------------------------
const handleFourthSelect = async (val) => {
  let urlView = "";
  let urlChart = "";

  if (firstSelect.value === "year") {
    const year = secondSelect.value;
    if (thirdSelect.value === "major") {
      if (Array.isArray(val) && val.length > 1) {
        urlView = "/system/sa/one-year-multi-major-view";
        urlChart = "/system/sa/one-year-multi-major-chart";
      } else {
        urlView = "/system/sa/one-year-one-major-view";
        urlChart = "/system/sa/one-year-one-major-chart";
      }
    } else if (thirdSelect.value === "teacher") {
      if (Array.isArray(val) && val.length > 1) {
        urlView = "/system/sa/one-year-multi-teacher-view";
        urlChart = "/system/sa/one-year-multi-teacher-chart";
      } else {
        urlView = "/system/sa/one-year-one-teacher-view";
        urlChart = "/system/sa/one-year-one-teacher-chart";
      }
    }
  } else if (firstSelect.value === "major") {
    const years = Array.isArray(thirdSelect.value)
        ? thirdSelect.value
        : [thirdSelect.value];
    if (years.length > 1) {
      urlView = "/system/sa/one-major-multi-year-view";
      urlChart = "/system/sa/one-major-multi-year-chart";
    } else {
      urlView = "/system/sa/one-year-one-major-view";
      urlChart = "/system/sa/one-year-one-major-chart";
    }
  } else if (firstSelect.value === "teacher") {
    const years = Array.isArray(thirdSelect.value)
        ? thirdSelect.value
        : [thirdSelect.value];
    if (years.length > 1) {
      urlView = "/system/sa/one-teacher-multi-year-view";
      urlChart = "/system/sa/one-teacher-multi-year-chart";
    } else {
      urlView = "/system/sa/one-year-one-teacher-view";
      urlChart = "/system/sa/one-year-one-teacher-chart";
    }
  }

  if (urlView && urlChart) {
    loadViewData(urlView);
    loadChartData(urlChart);
  }
};

// ---------------------------
// 加载数据
// ---------------------------
const loadViewData = async (url) => {
  const { data } = await axios.get(url);
  tableData.value = data.list || [];
};
const loadChartData = async (url) => {
  const { data } = await axios.get(url);
  drawCharts(data);
};

// ---------------------------
// 绘制图表
// ---------------------------
const drawCharts = (chartData) => {
  nextTick(() => {
    if (!radarChart) radarChart = echarts.init(radarChartRef.value);
    if (!barLineChart) barLineChart = echarts.init(barLineChartRef.value);

    radarChart.setOption({
      title: { text: "综合能力雷达图" },
      tooltip: {},
      radar: {
        indicator: chartData.indicators || [],
      },
      series: [
        {
          type: "radar",
          data: [{ value: chartData.values || [], name: "综合分布" }],
        },
      ],
    });

    barLineChart.setOption({
      title: { text: "维度得分统计" },
      tooltip: {},
      xAxis: { type: "category", data: chartData.categories || [] },
      yAxis: { type: "value" },
      series: [
        {
          type: chartData.type || "bar",
          data: chartData.series || [],
        },
      ],
    });
  });
};
</script>

<style scoped>
.statistics-analysis-page {
  padding: 24px;
  background: #f9f7f3;
}
.page-title {
  font-size: 22px;
  font-weight: bold;
  color: #3a7bd5;
  margin-bottom: 16px;
}
.filter-card {
  margin-bottom: 24px;
  padding: 16px;
}
.filter-row {
  display: flex;
  flex-wrap: wrap;
  gap: 16px;
}
.chart-container {
  display: flex;
  flex-direction: column;
  gap: 24px;
}
.chart {
  height: 360px;
  border-radius: 16px;
  background: #fff;
  box-shadow: 0 2px 6px rgba(0, 0, 0, 0.05);
}
.table-card {
  margin-top: 24px;
}
</style>
